package ita.class1.group2.supermarket.merchant.controller;


import ita.class1.group2.supermarket.common.annotation.Component;
import ita.class1.group2.supermarket.common.annotation.RequestMapping;
import ita.class1.group2.supermarket.common.pojo.ResponseMessage;
import ita.class1.group2.supermarket.common.util.FileUtil;
import ita.class1.group2.supermarket.common.util.JsonUtil;
import ita.class1.group2.supermarket.common.util.UUIDUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;

import java.io.File;
import java.io.InputStream;
import java.util.List;

@Component
public class FileUploadController {

    private static final String ERROR_MSG ="文件上传错误";

    @RequestMapping("/file/upload")
    public String fileUpload(List<FileItem> fileItems) throws Exception {
        ResponseMessage responseMessage = new ResponseMessage();
        String newFileName = null;
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {
                String folder = FileUtil.getUploadFolder().getAbsolutePath();
                InputStream in = item.getInputStream();
                newFileName = FileUtil.copyFileInput(in, folder, item.getName());
                if(newFileName!=null){
                    responseMessage.setResultCode(200);
                    responseMessage.setMessage(newFileName);
                }
                else{
                    responseMessage.setResultCode(500);
                    responseMessage.setMessage(ERROR_MSG);
                }
            }
        }
        return JsonUtil.obj2json(responseMessage);
    }

}
